<?php
class Builder extends CI_Controller
{
	var $url_alias;
	var $selected_article;
	var $selected_category;
	var $menu_type;
	var $site_title;
	var $site_meta_description;
	var $site_meta_keywords;
	var $data;
	public $menu_item_id;
	
	function __construct()
	{
		parent::__construct();
		$this->load->model("builders/builder_model", "builder");
	}	
	function index()
	{
		
		
		$this->url_alias = $this->uri->segment(1);
		
		$this->parser->parse("template/header", $this->builder->getHeaderParams());
	
		
		if(!$this->url_alias)
		{
			$this->parser->parse("template/frontpage", $this->builder->getFrontpageParams());
		}
		else 
		{
			if($this->checkAlias())
			{
				if($this->menu_type->num_rows() > 0)
				{
					switch ($this->menu_type->row()->title)
					{
						case "article":
							$article = $this->db->query("SELECT * FROM articles WHERE alias='$this->url_alias'")->row();
							$data['article:title'] = $article->title;
							$data['article:fulltext'] = $article->fulltext;
							$this->parser->parse("template/article/default", $data);
							break;
						case "category":
							$this->load->model("managers/category_manager", "category");
							$category = $this->db->get_where("categories", array("alias" => $this->url_alias))->row();
							$data['articles'] = $this->category->getArticles($category->id);
							$data['category-name'] = $category->title;
							$this->parser->parse("template/category/default", $data);
							break;
						default:
							
						break;
					}
				}
				else {
						$article = $this->db->query("SELECT * FROM articles WHERE alias='$this->url_alias'")->row();
						$data['article:title'] = $article->title;
						$data['article:fulltext'] = $article->fulltext;
						$this->parser->parse("template/article/default", $data);
				}
			}
			else
			{
				show_404();
			}	
		}
		$this->load->view("template/footer");
	}
	
	private function checkAlias()
	{
		$menu_type = $this->db->query("SELECT * FROM menu_types WHERE menu_types.id IN 
										(SELECT menu_type_id FROM menu_items WHERE alias='$this->url_alias')");
		$article = $this->db->query("SELECT * FROM articles WHERE alias='$this->url_alias'");

		if ($menu_type->num_rows() > 0 || $article->num_rows() > 0)
		{
			$this->menu_type = $menu_type;
			return TRUE;
		}
		else
		{
			return FALSE;
		}
	}
}